#include "flag_lab_cbx.h"
#include <QHBoxLayout>
#include <QDebug>

Flag_Lab_Cbx::Flag_Lab_Cbx(const QJsonObject &flagDetails, QWidget *parent)
    : QWidget(parent)
{
    setupControlLayout(flagDetails);
}

void Flag_Lab_Cbx::setupControlLayout(const QJsonObject &flagDetails)
{
    QHBoxLayout *mainLayout = new QHBoxLayout(this);
    mainLayout->setContentsMargins(0, 0, 0, 0);

    QJsonObject comboBoxDetails = flagDetails["combobox"].toObject();
    QStringList options = comboBoxDetails["option"].toVariant().toStringList();
    if (options.isEmpty()) return;

    QWidget *btnContainer = new QWidget(this);
    btnContainer->setObjectName("btnContainer");
    btnContainer->setStyleSheet(R"(
        #btnContainer {
            background-color: #2e3a50;
            border-radius: 20px;
            padding: 6px;
        }
    )");

    QHBoxLayout *btnLayout = new QHBoxLayout(btnContainer);
    btnLayout->setContentsMargins(12, 6, 12, 6);  // 增加内边距
    btnLayout->setSpacing(8);                    // 按钮之间间距更大

    for (int i = 0; i < options.size(); ++i) {
        QString text = options[i];
        QPushButton *btn = new QPushButton(text, this);
        btn->setFixedHeight(40);  // 高度可以调节
        btn->setStyleSheet(styleForButton(i == 0));  // 第一个默认选中
        btnLayout->addWidget(btn);
        buttons.append(btn);

        connect(btn, &QPushButton::clicked, this, [=]() {
            for (int j = 0; j < buttons.size(); ++j) {
                buttons[j]->setStyleSheet(styleForButton(buttons[j] == btn));
            }
            emit optionSelected(text);
            qDebug() << "Selected option:" << text;
        });
    }

    mainLayout->addWidget(btnContainer);
    setLayout(mainLayout);
}

QString Flag_Lab_Cbx::styleForButton(bool selected)
{
    QString base = R"(
        QPushButton {
            padding: 4px 20px;
            font-weight: bold;
            font-size: 18px;
            border: none;
            border-radius: 20px;
            background-color: )" + QString(selected ? "#2196f3" : "transparent") + R"(;
            color: )" + QString(selected ? "white" : "#ccc") + R"(;
        }
        QPushButton:hover {
            background-color: #3a4760;
            border-radius: 20px;
        }
    )";
    return base;
}
